<template>
    <eui-page-frame :topHeight="250" :withOutBorder="true">
        <template #top>
            <eui-navbar ref="EuiNavBar" title="有订单收货" :storeName="getRelatedName('rdsStores', sUserStore)"
                :storeId="sUserStore" @onClickStore="clickStore" color="#000000" backgroundColor="#FFFFFF">
                <template v-slot:popupContent>
                    <view class="custom-menu">
                        <view class="popup-icon-btn icon_new_count" @tap="onClickNewCount">
                            <icon class="icon enjoyIcon icon-jia" />
                            <text>我要收货</text>
                        </view>
                        <view class="popup-icon-btn icon_new_count" @tap="onClickBatchRec">
                            <icon class="icon enjoyIcon icon-jia" />
                            <text>集单收货</text>
                        </view>
                    </view>
                </template>
            </eui-navbar>
            <view class="top-view">
                <eui-search-bar :foucs="true" ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码、订单号、供应商"
                    leftIcon="icon-saoyisao" :focus="true" @confirm="searchConfirm" @leftIconClick="scanCode"
                    radius="30" :showFilter="true">
                    <template v-slot:searchFields>
                        <view class="search-fields">
                            <view class="center">
                                <eui-card-input v-model="formData.c_status" title="单据状态" placeholder="请选择单据状态"
                                    :range="getDictSelectList('IO类单据状态')" type="radio" />
                                <eui-card-input v-model="formData.c_provider" title="供应商" type="text"
                                    placeholder="请输入供应商编码" />
                                <eui-card-input v-model="formData.c_mk_dt_s" title="开始日期" type="date"
                                    placeholder="请选择开始日期" rightIconType="clear" @iconClick="clear"
                                    singleTag="c_mk_dt_s" />
                                <eui-card-input v-model="formData.c_mk_dt_e" title="结束日期" type="date"
                                    placeholder="请选择结束日期" rightIconType="clear" @iconClick="clear"
                                    singleTag="c_mk_dt_e" />
                            </view>
                            <view class="bottom flex-1 flex">
                                <eui-button type="max" title="重置" singleTag="reset" @buttonClick="confirm" />
                                <eui-button type="max" title="确认" singleTag="fix" @buttonClick="confirm" />
                            </view>
                        </view>
                    </template>
                </eui-search-bar>
            </view>
        </template>
        <eui-page-content>
            <eui-virtual-list refresher="true" :origList="dataList" isBottom="true" type="list" v-model="dataList"
                :title="false" templateTitle="" @itemClick="templateClick" @onRefresh="getData" @lower="templateLower"
                isImage :refresher="true" :checkboxShow="batchRec">
                <template v-slot:list="scope">
                    <!--                    <eui-text v-model="scope.c_po_id" type="id"/>-->
                    <!-- <eui-text type="status" :value="getDictName('收发货状态', scope.c_d_status)" class="" /> -->
                    <eui-text v-model="scope.c_po_id" type="name" title="订单号" cWidth="width: 100%" />
                    <eui-text v-model="scope.c_store_id" :name="getRelatedName('rdsStores', scope.c_store_id)"
                        type="titlename" title="目的机构" cWidth="width: 100%"  />
                    <eui-text v-model="scope.c_provider" :name="getRelatedName('rdsProviders', scope.c_provider)"
                        type="titlename" title="供应商" cWidth="width: 100%"  />
                    <!-- <eui-text v-model="scope.c_adno" :name="getRelatedName('rdsDeparts',scope.c_adno)" type="titlename" title="部门" occupy style="grid-template-columns: 100%;"/> -->
                    <eui-text v-model="scope.c_mk_userno" :name="getRelatedName('rdsUsers', scope.c_mk_userno)"
                        type="titlename" title="录入" />
                    <eui-text v-model="scope.c_mk_dt" type="rdstime" />
                    <eui-text v-model="scope.c_au_userno" type="titlename" title="审核"
                        :name="getRelatedName('rdsUsers', scope.c_au_userno)" v-if="scope.c_status === '3'" />
                    <eui-text v-model="scope.c_au_dt" type="rdstime" v-if="scope.c_status === '3'" />
                </template>
                <template v-slot:bottom="scope">
                    <view v-if="scope.c_status === '0' && scope.c_approve_status === '1'">
                        <eui-button :modelValue="scope" type="max" single-tag="submit" title="收货"
                            @buttonClick="buttonClick" />
                    </view>
                    <view v-if="scope.c_status === '0' && scope.c_approve_status === '1'">
                        <eui-button :modelValue="scope" type="max2" single-tag="audit"
                            :title="sysConfig.isApprove ? '审批' : '审核'" @buttonClick="buttonClick" />
                    </view>
                    <view v-if="['3', '8', '9'].includes(scope.c_status) || ['2'].includes(scope.c_approve_status)">
                        <eui-button :modelValue="scope" type="max" single-tag="detail" title="收货详情"
                            @buttonClick="buttonClick" />
                    </view>
                </template>
            </eui-virtual-list>
        </eui-page-content>
    </eui-page-frame>
</template>

<script setup type="ts">
import { ref, reactive, onMounted } from 'vue';
import dateRangUtil from '../../../common/dateRangUtil';
import service from "@/common/service";
import { getRelatedName, getDictSelectList } from '../components/RelatedName.js';
import { getRdsUrl, rdsRequest } from '@/hooks/rdsServices';
import { mapState, mapMutations } from 'vuex'
import { init, getRdsSysConfig } from '@/hooks/init'
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { onLoad } from "@dcloudio/uni-app";
import Enjoy from "@/common/enjoy";

const rdsUrl = getRdsUrl();
const mainStore = useMainStore();
const { loginInfo } = mainStore;
const loginStore = useLoginStore();

const RdsSearchBar = ref(null);
const EuiNavBar = ref(null);

const sUserStore = ref(''); // 用户默认机构编码
const sUserStoreName = ref(''); // 用户默认机构名称
const sUser = ref(''); // 当前用户编码
const searchText = ref('');
const CurrentPage = ref(1);  //第几页
const PageSize = ref(10);  //每页10条
const RowsCount = ref(0);  //总条数
const PageCount = ref(1);  //总页数
const displayable = ref(false); // true允许页面编辑
const batchRec = ref(false);//集单收货
// 查询表单
const formData = ref({
    c_mk_dt_s: (dateRangUtil.getLast1Month())[0],
    c_mk_dt_e: (dateRangUtil.getLast1Month())[1],
    c_po_type: '521',
    c_provider: '',
    c_po_id: '',
    c_status: '0'
});
const mainData = ref({});
const dataList = ref([]);
const sysConfig = ref({
    isApprove: '',//商品验收单是否审批
});


onLoad(async () => {
    await init();
    await getSysConfig();
    if (!loginInfo.sUserStore) {
        EuiNavBar.value.closeDrawer();
        return;
    }
    await setDefault();
    service.enjoyShowLoading('正在加载...');
    await getData();
    service.enjoyHideLoading();
    RdsSearchBar.value.clear();
})

const setDefault = async () => {
    sUserStore.value = loginInfo.sUserStore;
    sUserStoreName.value = loginInfo.sUserStoreName;
    sUser.value = loginInfo.sUser;
};
const getSysConfig = async () => {
    sysConfig.value.isApprove = await getRdsSysConfig("单据是否审批", "商品验收单") === '是';
};
const SelectionChanged = async (event) => {
    if (event.type === 'c_store_id') {
        // 更新机构信息
        sUserStoreName.value = event.c_store_id_name;
        sUserStore.value = event.c_store_id;
        // c_store_id = event.c_store_id;
        // 按新条件获取数据
        await getData();
    }
};
defineExpose({
    SelectionChanged
})

const clickStore = () => {
    let params = Enjoy.GetDialogParms();
    params.CallBack = SelectionStoreChanged;
    params.SelectionType = "机构选择";
    params.SelectedItems = sUserStore.value;
    Enjoy.OpenDialog(params)
}
const SelectionStoreChanged = async (event) => {
    if (event.SelectionType == '机构选择') {
        // 更新机构信息
        sUserStore.value = event.BackParms.Key;
    }
    // 按新条件获取数据
    await getData();
}
const clear = (e) => {
    switch (e) {
        case 'c_mk_dt_s':
            formData.value.c_mk_dt_s = '';
            break;
        case 'c_mk_dt_e':
            formData.value.c_mk_dt_e = '';
            break;
    }
}
const scanCode = () => {
    uni.scanCode({
        success: function (res) {
            if (res.result) {
                searchText.value = res.result;
                getData();
            }
        },
    });
}
const templateClick = async (e) => {
    let { index, item } = e;
    await uni.navigateTo({
        url: './orderDetail?c_po_id=' + item.c_po_id + '&c_id=' + item.c_id
    });
};

const getData = async (e) => {
    if (!e) {
        CurrentPage.value = 1;
    }
    const req = {
        IsNotPage: false,
        CurrentPage: CurrentPage.value,
        PageSize: PageSize.value,
        UserNo: loginInfo.sUser,
        WhereList: [
            { c_col: "c_store_id", c_oper: "等于", c_value: sUserStore.value, c_logic: "而且" },
            formData.value.c_mk_dt_s ? {
                c_col: "c_mk_dt",
                c_oper: "大于等于",
                c_value: formData.value.c_mk_dt_s,
                c_logic: "而且",
                c_col_dtype: "System.DateTime"
            } : {},
            formData.value.c_mk_dt_e ? {
                c_col: "c_mk_dt",
                c_oper: "小于等于",
                c_value: formData.value.c_mk_dt_e,
                c_logic: "而且",
                c_col_dtype: "System.DateTime"
            } : {},
            { c_col: "c_po_type", c_oper: "等于", c_value: formData.value.c_po_type, c_logic: "而且" },
            formData.value.c_provider ? {
                c_col: "c_provider",
                c_oper: "等于",
                c_value: formData.value.c_provider,
                c_logic: "而且"
            } : {},
            formData.value.c_po_id ? {
                c_col: "c_po_id",
                c_oper: "等于",
                c_value: formData.value.c_po_id,
                c_logic: "而且"
            } : {},
            { c_col: "c_status", c_oper: "等于", c_value: formData.value.c_status, c_logic: "而且" },
            { c_col: "c_src_id", c_oper: "不为空", c_value: '', c_logic: "而且" }
        ]
    }
    if (searchText.value) {
        let strLength = searchText.value.length;
        if (strLength > 6) {
            //判断是否包含英文
            const flag = await containsLetters(searchText.value);
            if (!flag) {
                strLength = 7;
            }
        }
        switch (strLength) {
            case 6://供应商
                req.WhereList.push({
                    c_col: "c_provider",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
            case 7: //商品编码
                req.WhereList.push({
                    c_col: "c_gcode",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
            case 13://订单号
                req.WhereList.push({
                    c_col: "c_po_id",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
            default:
                req.WhereList.push({
                    c_col: "c_gcode",
                    c_oper: "等于",
                    c_value: searchText.value,
                    c_logic: "而且",
                });
                break;
        }
    }
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyQueryList', req, '701');
    CurrentPage.value = result.CurrentPage; //第几页
    PageSize.value = result.PageSize; //每页10条
    RowsCount.value = result.RowsCount; //总条数
    PageCount.value = result.PageCount; //总页数
    if (result.CurrentPage == 1) {
        dataList.value = result.ReturnObject;
    } else {
        dataList.value = dataList.value.concat(result.ReturnObject);
    }
};
const clickLeft = async () => {
    uniBack();
};

const onClickNewCount = async (e) => {
    EuiNavBar.value.closeDrawer();
    await uni.navigateTo({
        url: './orderRec?storeId=' + sUserStore.value
    });
};

const onClickBatchRec = async (e) => {
    EuiNavBar.value.closeDrawer();
    await uni.navigateTo({
        url: './batchRec?storeId=' + sUserStore.value
    });
};
// 上拉加载更多
const templateLower = async () => {
    if (CurrentPage.value < PageCount.value) {
        CurrentPage.value = CurrentPage.value + 1;
        await getData(true);
    }
};
const searchConfirm = async (e) => {
    searchText.value = e.value.toUpperCase();
    await getData();
    if (dataList.value.length === 0 && searchText.value.length === 13) {
        //根据条码查询订单中商品的旧条码
       const gcode = await getBillGcode(searchText.value);
       if(gcode){
           searchText.value = gcode
           await getData();
       }
    }
};

// 获取单据详情信息
const getBillGcode = async (code) => {
    const result = await rdsRequest(rdsUrl.scApi, '商品验收单', 'QueryRecGByBarCode', code, '701');
    if (result) {
        return result.c_gcode;
    }
    return "";
};
const confirm = async (t) => {
    let { singleTag } = t;
    switch (singleTag) {
        case 'reset':
            formData.value.c_mk_dt_s = (dateRangUtil.getLast1Month())[0];
            formData.value.c_mk_dt_e = (dateRangUtil.getLast1Month())[1];
            formData.value.c_provider = '';
            formData.value.c_po_id = '';
            formData.value.c_status = '0';
            break;
        case 'fix':
            await getData();
            // 关闭弹出层
            RdsSearchBar.value.closeDrawer();
            break;
    }
};
//判断是否包含英文
const containsLetters = async (str) => {
    return /[a-zA-Z]/.test(str);
};
const buttonClick = async (e) => {
    let { singleTag, modelValue, type } = e;
    switch (singleTag) {
        case 'detail':
            await uni.navigateTo({
                // url: './partnerGdsRecDetail?c_id=' + v.c_id + '&storeId=' + sUserStore
                url: './detail?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
            });
            break;
        case 'audit':
            const req = {
                BillId: modelValue.c_id,
                UserNo: loginInfo.sUser,
                StoreId: modelValue.c_store_id,
            }
            mainData.value = modelValue;
            console.log("审批", sysConfig.value.isApprove);
            if (sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审批
                await approve(req);
            }
            if (!sysConfig.value.isApprove && mainData.value.c_status == '0') { // 审核
                await auditBill(req);
            }
            break;
        case 'submit':
            if (modelValue.c_status == '0' && modelValue.c_approve_status == '1') {
                //todo 如果验收单已经是集单收货，跳转到集单收货的页面
                const collectionResult = await queryRecCollectionByRecId(modelValue.c_id);
                console.log('collectionResult', collectionResult);
                if (!collectionResult) {
                    await uni.navigateTo({
                        url: './orderRec?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
                    });
                    return;
                } else {
                    await uni.showToast({
                        title: '该订单已集单收货，正在跳转...',
                        icon: 'none'
                    });
                    setTimeout(() => {
                        uni.navigateTo({
                            url: './batchRec?c_id=' + modelValue.c_id + '&storeId=' + sUserStore.value
                        });
                    }, 2000);
                }

            }
            break;
        case 'cancel':
            batchRec.value = false;
            break;
        case 'batchRec':
            const ids = dataList.value.filter(item => item.checked).map(item => item.c_id).join(',');
            if (ids.length <= 0) {
                await uni.showToast({
                    title: '请选择要收货的单据',
                    icon: 'none'
                });
                return;
            }
            await uni.navigateTo({
                url: './batchRec?c_id=' + ids + '&storeId=' + sUserStore.value
            });
            break;
    }
};
// 审批
const approve = async (req) => {
    if (mainData.value.c_approve_status == "1") {
        uni.showModal({
            title: ' 提示',
            content: '请确认，单据[' + req.BillId + ']发起审批?',
            showCancel: true,
            success: async (res) => {
                if (res.confirm) {
                    await sendApprove();
                }
            }
        });
    } else {
        const item = {
            c_approve_status: mainData.value.c_approve_status,
            Id: mainData.value.c_id,
            UserNo: loginInfo.sUser,
            StoreId: mainData.c_store_id,
            AppParam: '商品验收单',
        }
        const request = {
            Id: req.BillId,
            UserNo: loginInfo.sUser,
            StoreId: mainData.value.c_store_id,
        }
        // apps.ApprovePath(request, item, res => { }, res => { });
    }
};
const auditBill = async (req) => {
    if (mainData.value.c_status == '0') {
        uni.showModal({
            title: ' 提示',
            content: '请确认，审核单据[' + req.BillId + ']?',
            showCancel: true,
            success: async (res) => {
                if (res.confirm) {
                    service.enjoyShowLoading('正在审核...');
                    await rdsRequest(rdsUrl.scApi, '商品验收单', 'EnjoyBillAudit', req, '701');
                    service.enjoyHideLoading();
                    await uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: '审核成功！'
                    });
                    await getData();
                }
            }
        });
    }
};

const sendApprove = async () => {
    const ApproveBills = {
        AppPage: "/modules/ic/rec/rec/list",
        AppParam: "商品验收单",
        AppUsers: [],
        BillId: mainData.value.c_id,
        BillKey: mainData.value.c_id,
        BillRealType: "商品验收单",
        BillType: "商品验收单",
        CFGName: "商品验收单",
        FlowGuid: "",
        FlowName: "商品验收单",
        HtmlContent: "",
        HtmlMobileContent: "",
        IsMainFlow: true,
        IsCanTempApp: false,
        IsSelected: true,
        IsTempApp: false,
        MdCode: "rds_ic_gds_rec",
        NoticType: "邮件",
        ProjectName: "RDS", // OA\RMIS\RMISNew,
        StoreId: mainData.value.c_store_id,
        AppReqUserNo: loginInfo.sUser,
        UserNo: loginInfo.sUser,
        TempTitle: `单据:${mainData.value.c_id}`,
        // ApproveServiceUrl: Url.EnjoyRMIS,
    }
    const approveResult = await rdsRequest(rdsUrl.apiApi, '审批处理', 'SendApprove', ApproveBills, '701');
    if (approveResult.Result) {
        await uni.showToast({
            duration: 2000,
            icon: 'none',
            title: '发送审批成功！'
        });
        await getData();
    }
};
// 获取集单数据
const queryRecCollectionByRecId = async (billId) => {
    if (!billId) {
        return;
    }
    const result = await rdsRequest(rdsUrl.scApi, '集单收货', 'EnjoyBillQueryByRecId', billId, '');
    if (result.ds.length > 0) {
        return result;
    }
    return null;
};
</script>

<style lang="scss" scoped>
@import '../../../main.scss';
@import '@/static/font/enjoyicon/iconfont.css';

::v-deep .white-main {
    margin: 20rpx 0;
}

.custom-menu {
    border-top: 1px solid rgba(0, 0, 0, .1);
    display: flex;
    flex: 1;
    width: 100%;
    justify-content: flex-start;
}


.popup-icon-btn {
    display: flex;
    padding: 10px;
    margin: 5px;
    color: #333333;
    text-align: center;
    flex-direction: column;
}

.popup-icon-btn uni-icon {
    margin: 0 auto;
    background: #ffffff;
    border-radius: 50%;
    font-size: 1.2em;
    width: 42px;
    height: 42px;
    line-height: 42px;
    text-align: center;
}

.popup-icon-btn uni-text {
    font-size: 0.8em;
    padding: 0.2em 0;
    line-height: 1.4em;
    width: 52px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

.icon_new_count {
    color: #00aaff;
}

.top-view {
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
}

.main-view {
    flex: 1;
    flex-direction: column;
}

.search-fields {
    width: 100%;
    background: #FFFFFF;
    position: relative;

    .bottom {
        background: #ffffff;
        border-top: 1rpx solid $uni-line-color;
        display: flex;
        justify-content: center;
        padding: 20rpx;
    }
}
</style>
